﻿#pragma execution_character_set("utf-8")
#include "dialogmoveplatform.h"
#include "ui_dialogmoveplatform.h"
#include <QMessageBox>
#include <QElapsedTimer>
#include <QThread>
#include <QComboBox>
#include <QListWidgetItem>
#include <QString>
#include <QSpinBox>

#include "CL2CRSDriveControl.h"
#include "DeviceManager.h"
#include "WidgetUtils.h"
#include "dialogmoveplatform.h"
#include "tablewidgetutils.h"
//#include "GlobalVar.h"

DialogMovePlatform::DialogMovePlatform(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogMovePlatform)
{
    ui->setupUi(this);
    startTimer(2000);
    // 下拉框
    InitTable();
    this->setWindowFlags(windowFlags()|Qt::WindowMinMaxButtonsHint);
}

void  DialogMovePlatform::InitTable()
{
    TableWidgetUtils::SetHeader(ui->tableWidgetLimit,QStringList()<<"点位"<<"功能"<<"极性");
    ui->tableWidgetLimit->setRowCount(2);
    for(int i=0;i<2;i++)
    {
        QTableWidgetItem *item0 = new QTableWidgetItem(QString("DO %1").arg(i));
        ui->tableWidgetLimit->setItem(i,0,item0);
        TableWidgetAddComboBox(ui->tableWidgetLimit,i,1,QStringList()<<"正限位"<<"负限位",0);
        TableWidgetAddComboBox(ui->tableWidgetLimit,i,2,QStringList()<<"open"<<"close",0);
    }
}

//TableWidget中加入下拉框,并设置下拉框的内容及初始下标
void DialogMovePlatform::TableWidgetAddComboBox(QTableWidget *tableWidget,int x, int y, QStringList items,int comboBoxIdx)
{
    QComboBox *combox = new QComboBox();
    combox->addItems(items);
    combox->setCurrentIndex(comboBoxIdx);				//下拉框初始下标
    tableWidget->setCellWidget(x,y,(QWidget*)combox);
}

DialogMovePlatform::~DialogMovePlatform()
{
    delete ui;
}

void DialogMovePlatform::SetDevice(BaseMotorController *platform)
{
    _movePlatform=platform;
}

void DialogMovePlatform::timerEvent(QTimerEvent *event)
{
    Q_UNUSED(event);
    if(!ui->chbAutoUpdate->isChecked())
    {
        return;
    }
    QElapsedTimer ela;
    ela.start();
    QList<StateItem> items=_movePlatform->GetStateItems();
//    qDebug()<<__FUNCTION__<<__LINE__<<ela.elapsed()<<"ms";
    if(ui->tableWdigetState->rowCount()!=items.count())
    {
        ui->tableWdigetState->setRowCount(0);
        TableWidgetUtils::SetHeader(ui->tableWdigetState,QStringList()<<"类型"<<"状态"<<"标注");

        QMap<int,int> map={
            {0,100},
            {1,100}
        };
        TableWidgetUtils::SetTableWidgetWidth(ui->tableWdigetState,map);
        ui->tableWdigetState->horizontalHeader()->setSectionResizeMode(2,QHeaderView::Stretch);

        ui->tableWdigetState->setRowCount(items.count());
        for(int row=0;row<items.count();row++)
        {
            StateItem item=items.at(row);
            QStringList vals={item.Name,item.State,item.Annotation};

            for(int col=0;col<vals.count();col++)
            {
                QTableWidgetItem *newItem1 = new QTableWidgetItem();
                newItem1->setData(Qt::DisplayRole,QVariant(vals.at(col)));
                newItem1->setTextAlignment(Qt::AlignCenter);
                ui->tableWdigetState->setItem(row,col,newItem1);
            }
        }
    }
    for(int i=0;i<items.count();i++)
    {
        ui->tableWdigetState->item(i,1)->setText(items.at(i).State);
    }
}

void DialogMovePlatform::closeEvent(QCloseEvent *event)
{
    ui->chbAutoUpdate->setChecked(false);
    if(!_isSaved)
    {
        // 在这里执行关闭事件的处理
        if(QMessageBox::question(this, "提示", "是否保存参数?",QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
        {
            SaveParam();
        }
    }
    event->accept();
}

void DialogMovePlatform::on_btnMotorOpen_clicked()
{
    _movePlatform->SetMotorEnable(true);
}

void DialogMovePlatform::on_btnMotorClose_clicked()
{
    _movePlatform->SetMotorEnable(false);
}

void DialogMovePlatform::on_IDC_Btn_RunVel_Set_clicked()
{
    _movePlatform->SetVelocity(VEL_TOPSPEED,ui->spinVel->value());
}

void DialogMovePlatform::on_IDC_Btn_AbsoluteMove_clicked()
{
    _movePlatform->AbsoluteMove(ui->spinAbsMove->value());
}

void DialogMovePlatform::on_IDC_Btn_StopMove_clicked()
{
    _movePlatform->Stop();
}

void DialogMovePlatform::on_IDC_Btn_ResetZeroCor_clicked()
{
    _movePlatform->SetCurrentPositionToZero();
}

void DialogMovePlatform::on_IDC_Btn_RelativeMoveForward_clicked()
{
    WidgetUtils::Execute(sender(),[this]()
    {
        double dRelativeMove = ui->spinRealtiveMove->value();
        this->_movePlatform->RelativeMove(dRelativeMove);
    });
}

void DialogMovePlatform::on_IDC_Btn_RelativeMoveReverse_clicked()
{
    //反向移动
    WidgetUtils::Execute(sender(),[this]()
    {
        double dRelativeMove = ui->spinRealtiveMove->value();
        this->_movePlatform->RelativeMove(-dRelativeMove);
    });
}


void DialogMovePlatform::on_radAxisX_clicked(bool checked)
{
    if(checked)
    {
         _movePlatform->SetCurrentAxisType(BaseMotorController::AXIS_X);
    }
}

void DialogMovePlatform::on_radAxisY_clicked(bool checked)
{
    if(checked)
    {
         _movePlatform->SetCurrentAxisType(BaseMotorController::AXIS_Y);
    }
}

void DialogMovePlatform::on_radAxisZ_clicked(bool checked)
{
    if(checked)
    {
         _movePlatform->SetCurrentAxisType(BaseMotorController::AXIS_Z);
    }
}

void DialogMovePlatform::on_btnSetLimit_clicked()
{
    QList<MotorIOItem> items=GetMotorIOItems();
    _movePlatform->SetLimit(items);
}

QList<MotorIOItem> DialogMovePlatform::GetMotorIOItems()
{
    QList<MotorIOItem> ret;
    QMap<QString,uint16_t> funcMap={
        {"正限位",0x25},
        {"负限位",0x26}
    };
    QMap<QString,PolartyType> polarType={
        {"open",PolartyType::Open},
        {"close",PolartyType::Close}
    };
    for(int i=0;i<ui->tableWidgetLimit->rowCount();i++)
    {
        MotorIOItem mi;
        mi.Name=ui->tableWidgetLimit->item(i,0)->text();
        QComboBox* myCmb1=dynamic_cast<QComboBox*>(ui->tableWidgetLimit->cellWidget(i,1));
        mi.FunctionType=funcMap[myCmb1->currentText()];
        QComboBox* myCmb2=dynamic_cast<QComboBox*>(ui->tableWidgetLimit->cellWidget(i,2));
        mi.PloartyType=polarType[myCmb2->currentText()];
        ret.append(mi);
    }
    return ret;
}

void DialogMovePlatform::on_btnReturnToZero_clicked()
{
    if(!ui->radForward->isChecked()&&!ui->radBack->isChecked())
    {
        return;
    }
    if(!ui->radLimit->isChecked()&&!ui->radZero->isChecked())
    {
        return;
    }
    auto direction=ui->radForward->isChecked()?BaseMotorController::Forward:BaseMotorController::Back;
    auto limit=ui->radLimit->isChecked()?BaseMotorController::Limit:BaseMotorController::Zero;
    _movePlatform->ReturnToZero(direction,limit);
}

void DialogMovePlatform::on_btnSetCurPosZero_clicked()
{
    _movePlatform->SetCurrentPositionToZero();
}

void DialogMovePlatform::SaveParam()
{
    _isSaved=true;
    _movePlatform->SaveParam();
//    QSettings *set=GlobalVar::Instance().Setting;
//    set->beginGroup("MovePlatform");
//    double pos;
//    _movePlatform->GetPosition(pos);
//    set->setValue("Postion",pos);
//    set->endGroup();
//    set->sync();
//    _movePlatform->SaveParam();
}

void DialogMovePlatform::on_btnSaveParam_clicked()
{
    SaveParam();
}

void DialogMovePlatform::on_btnResetFactory_clicked()
{
    _movePlatform->Reset();
}


void DialogMovePlatform::on_IDC_Btn_SetMaxElectricity_clicked()
{
    _movePlatform->SetMaxElectricity(ui->spinMaxElectricity->value());
}

void DialogMovePlatform::on_btnSetAxisDirection_clicked()
{
    BaseMotorController::AxisDirectionType dt=ui->cmbAxisDirection->currentText()=="正向"?
                BaseMotorController::AxisForward:BaseMotorController::AxisReverse;
    _movePlatform->SetAxisDriection(dt);
}

QSettings * DialogMovePlatform::GetQSetings()
{
    QJsonObject mainObj=JsonUtils::LoadMainConfig();
    QString deviceType=mainObj["DeviceType"].toString();

    QString initFile=QString("./Config/%1/%2").arg(deviceType,"ClientConfig.ini");
    QSettings *set=new QSettings(initFile,QSettings::IniFormat);

    return set;
}

void DialogMovePlatform::on_btnSaveFocus_clicked()
{
    QSettings *set = GetQSetings();

    set->beginGroup("MovePlatform");
    double dpos;
    _movePlatform->GetPosition(dpos);
    if(ui->radAxisX->isChecked())
    {
        set->setValue("AxisX",dpos);
    }
    else if(ui->radAxisY->isChecked())
    {
        set->setValue("AxisY",dpos);
    }
    else if(ui->radAxisZ->isChecked())
    {
        set->setValue("AxisZ",dpos);
    }
    set->endGroup();
    set->sync();
    set->deleteLater();

    QMessageBox::information(this, "提示", "焦点位置保存成功",QMessageBox::Ok);
}

void DialogMovePlatform::on_btnLoadFocus_clicked()
{
    QSettings *set = GetQSetings();
    set->beginGroup("MovePlatform");
    double dpos;
    if(ui->radAxisX->isChecked())
    {
        dpos=set->value("AxisX",0).toDouble();
    }
    else if(ui->radAxisY->isChecked())
    {
        dpos=set->value("AxisY",0).toDouble();
    }
    else if(ui->radAxisZ->isChecked())
    {
        dpos=set->value("AxisZ",0).toDouble();
    }
    ui->spinAbsMove->setValue(dpos);
    set->endGroup();
    set->sync();
    set->deleteLater();
}
